package com.dd.framework.security.config;

import com.dd.framework.security.component.*;
import com.dd.framework.security.jwt.JwtAuthTokenFilter;
import com.dd.framework.security.jwt.JwtTokenHelper;
import com.dd.framework.security.jwt.property.JwtTokenConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * springsecurity 配置
 */
public abstract class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public IgnoreUrlsConfig ignoreUrlsConfig;


    /**
     * 获取jwt配置对象
     * @return
     */
    public abstract JwtTokenConfig jwtTokenConfig();

    /**
     * 获取用户信息查询对象
     * @return
     */
    public abstract UserDetailsService userDetailsService();


    /**
     * 添加认证拦截器
     * @param auth
     * @throws Exception
     */
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 使用自定义登录身份认证组件
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoderBean());
    }

    /**
     * 添加权限控制拦截器
     * @param httpSecurity
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {

        //配置不需要验证的请求地址
        for (String url : ignoreUrlsConfig.getUrls()){
            httpSecurity.authorizeRequests().antMatchers(url).permitAll();
        }

        // 关闭跨站请求防护
        httpSecurity.csrf().disable()
                .authorizeRequests()
                //允许跨域请求的OPTIONS请求
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                // 其他所有请求需要身份认证
//                .anyRequest().authenticated()
                .anyRequest().permitAll()
                .and()
                //设置session创建策略，不创建session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        //设置未登录处理器
        httpSecurity.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint());

        //用户无权访问处理器
        httpSecurity.exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler());

        //自定义jwt过滤器--用以用户身份认证
        httpSecurity.addFilterBefore(jwtAuthTokenFilter(),UsernamePasswordAuthenticationFilter.class);

        //设置动态权限验证拦截器
        httpSecurity.addFilterBefore(dynamicSecurityInterceptor(),FilterSecurityInterceptor.class);
//        // 退出登录处理器
//        httpSecurity.logout().logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler());
//        // 开启登录认证流程过滤器
//        httpSecurity.addFilterBefore(new JwtLoginFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
//        // 访问控制时登录状态检查过滤器
//        httpSecurity.addFilterBefore(new JwtAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);

    }

    @Bean
    public PasswordEncoder passwordEncoderBean() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public JwtAuthTokenFilter jwtAuthTokenFilter(){
        JwtAuthTokenFilter jwtTokenFilter = new JwtAuthTokenFilter(this.jwtTokenConfig(),jwtTokenHelper());
        jwtTokenFilter.setUserDetailsService(this.userDetailsService());
        return jwtTokenFilter;
    }

    @Bean
    public JwtTokenHelper jwtTokenHelper(){
        return new JwtTokenHelper();
    }

    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint(){
        return new MallAuthenticationEntryPoint();
    }

    @Bean
    public AccessDeniedHandler accessDeniedHandler(){
        return new MallAccessDeniedHandler();
    }

    @Bean
    public MallDynamicSecurityInterceptor dynamicSecurityInterceptor(){
        MallDynamicSecurityInterceptor mallDynamicSecurityInterceptor = new MallDynamicSecurityInterceptor();
        mallDynamicSecurityInterceptor.setDynamicSecurityMetadataSource(mallDynamicSecurityMetadataSource());
        mallDynamicSecurityInterceptor.setIgnoreUrlsConfig(ignoreUrlsConfig);
        return mallDynamicSecurityInterceptor;
    }

//    @Bean
//    public IgnoreUrlsConfig ignoreUrlsConfig() {
//        return new IgnoreUrlsConfig();
//    }

    @Bean
    public MallDynamicSecurityMetadataSource mallDynamicSecurityMetadataSource(){
        return new MallDynamicSecurityMetadataSource();
    }

    @Bean
    public MallAccessDecisionManager accessDecisionManager(){
        return new MallAccessDecisionManager();
    }



}
